// Block File Copy
// By Ben 21:10 21/09/2016
#include <iostream>
#include <Windows.h>

using namespace std;
using std::cout;
using std::endl;

#define COMPLEATE 0
#define READ_ERROR 1
#define WRITE_ERROR 2
#define FILE_PATH_SAME 3
#define COPY_FAIL 4

char Messages[5][100] = {
	"File Copy Complete",
	"Cannot Read Source.",
	"Cannot Create Output.",
	"Source And Destination Cannot Be The Same.",
	"IO_ERROR Copy Faild"
};

int MyFileCopy(string src, string dest, int chunksize = 1024){
	FILE *fin = NULL;
	FILE *fout = NULL;
	char *Buffer = NULL;
	size_t BytesRead = 0;
	size_t BytesWrite = 0;

	//Compare input and output
	if (_stricmp(src.c_str(), dest.c_str()) == 0){
		//Output and source are the same.
		return FILE_PATH_SAME;
	}

	//Open source file.
	fin = fopen(src.c_str(), "rb");

	if (!fin){
		return READ_ERROR;
	}

	//Open file for writeing
	fout = fopen(dest.c_str(), "wb");

	if (!fout){
		fclose(fin);
		return WRITE_ERROR;
	}

	//Resize Buffer
	Buffer = new char[chunksize];
	//Do file copy.

	//Get first data
	BytesRead = fread(Buffer, sizeof(char), chunksize, fin);

	//While not end of file read
	while (!feof(fin)){
		//Write data
		BytesWrite = fwrite(Buffer, sizeof(char), BytesRead, fout);
		//Read in new data.
		BytesRead = fread(Buffer, sizeof(char), chunksize, fin);
	}
	//Write remaining data.
	BytesWrite = fwrite(Buffer, sizeof(char), BytesRead, fout);

	//Check if ReadByte and WriteByte are the same.
	if (BytesWrite != BytesRead){
		return COPY_FAIL;
	}

	//Tidy up time.
	fclose(fout);
	fclose(fin);

	delete[]Buffer;
	return COMPLEATE;
}

int main(int argc, char *argv[]){
	//Do file copy
	int Result = MyFileCopy("C:\\ben\\BloodCM.grp", "C:\\ben\\Blood10gr", 65535);
	
	//Test result.
	if (Result != COMPLEATE){
		cout << Messages[Result] << endl;
		system("pause");
		exit(1);
	}

	//File done message
	cout << Messages[Result] << endl;

	system("pause");
	return 0;
}